import React, { useState, useEffect, useCallback } from 'react';
import PropTypes from 'prop-types';
import './Box.scss';

const Box = ({ title, options, introduces, children }) => {
    const [index, setIndex] = useState(0);
    let timer = null;

    const tabOptionHandler = (idx) => {
        setIndex(idx);
    };

    const mouseoverHandler = () => {
        suspend();
    };

    const mouseoutHandler = () => {
        begin();
    };

    const begin = useCallback(() => {
        // eslint-disable-next-line react-hooks/exhaustive-deps
        timer = setInterval(() => {
            setIndex((prevIndex) => (prevIndex < options.length - 1 ? prevIndex + 1 : 0));
        }, 5000);
    }, [options.length]);

    const suspend = () => {
        clearInterval(timer);
    };

    useEffect(() => {
        begin();
        return () => {
            clearInterval(timer);
        };
    }, [begin, timer]);

    return (
        <div className="box_container" onMouseOver={mouseoverHandler} onMouseOut={mouseoutHandler}>
            <div className="title_bar">
                <div className="options_box">
                    <div className="options">
                        {options.map((o, i) => (
                            <div
                                key={o.name}
                                className={index === i ? 'current' : ''}
                                onClick={() => tabOptionHandler(i)}
                            >
                                {o.label}
                            </div>
                        ))}
                    </div>
                </div>
                <div className="title">
                    <span className="title_icon"></span>
                    <span>{title}</span>
                </div>
            </div>
            {introduces.length > 0 && (
                <ul className="introduce">
                    {introduces.map((introduce) => (
                        <li key={introduce.label}>
                            <span className="label">{introduce.label} </span>
                            <span className="num">{introduce.value}</span>
                            <span className="unit">{introduce.unit}</span>
                        </li>
                    ))}
                </ul>
            )}
            <div className="box_content">
                {children}
            </div>
        </div>
    );
};

Box.propTypes = {
    title: PropTypes.string,
    options: PropTypes.arrayOf(PropTypes.shape({
        name: PropTypes.string,
        label: PropTypes.string,
    })),
    introduces: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string,
        value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        unit: PropTypes.string,
    })),
    children: PropTypes.node,
};

Box.defaultProps = {
    title: '',
    options: [],
    introduces: [],
    children: null,
};

export default Box;
